<template>
  <div class="center-section-content">
    <div class="device-content">
      <div class="dialog-title">{{pointName}}</div>
      <div class="points-content clearfix">
        <div class="content-item">
          <div
            class="content-item-points"
            v-for="item in points"
            :key="item.id"
          >
            <img class="unit-img" :src="item.img" alt="" />
            <span class="unit-name">{{ item.name }}</span>
            <span class="unit-num">{{ item.num }}</span>
          </div>
        </div>
        <div class="content-item">
          <div class="layout-item" >
            <div class="title">空气质量指数</div>
            <div class="air-value fonts-DIN">45</div>
            <div class="air-level">优</div>
            <div class="air-time fonts-DIN">{{updateTime}}</div>
          </div>
          <div class="layout-item">
            <div class="item" v-for="item in evnResults" :key="item.id">
              <div class="item-content clearfix">
                <div class="item-label pull-left">
                  <div>{{ item.pointName }}</div>
                  <div class="item-value fonts-DIN">{{ item.pointValue }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="content-item">
          <div class="container">
            <div class="content-video" v-if="hongwai.length>0">
              <div class="video-grid">
                <div class="video-item">
                  <video
                    class="hide-progress-bar"
                    controls="false"
                    autoplay
                    loop
                    :src="hongwai[0].fileUrl"
                    controlsList="nodownload"
                    preload="auto"
                  >
                    您的浏览器不支持 video 标签。
                  </video>
                </div>
              </div>
            </div>
            <div class="content-video" v-if="hongwai.length>1">
              <div class="video-grid">
                <div class="video-item">
                  <video
                          class="hide-progress-bar"
                          controls="false"
                          autoplay
                          loop
                          :src="hongwai[1].fileUrl"
                          controlsList="nodownload"
                          preload="auto"
                  >
                    您的浏览器不支持 video 标签。
                  </video>
                </div>
              </div>
            </div>
            <div class="content-video" v-if="hongwai.length>2">
              <div class="video-grid">
                <div class="video-item">
                  <video
                          class="hide-progress-bar"
                          controls="false"
                          autoplay
                          loop
                          :src="hongwai[2].fileUrl"
                          controlsList="nodownload"
                          preload="auto"
                  >
                    您的浏览器不支持 video 标签。
                  </video>
                </div>
              </div>
            </div>
            <div class="audio-card" id="card" @click="playAudio()" v-if="shengwen">
              <img
                :src="shengwen.avatar"
                alt="音乐封面"
                class="audio-image"
              />
              <div class="audio-content">
                <!-- <div class="audio-info">
                  <h3>斑鸠</h3>
                  <div class="time-display" id="time1">0:00 / 0:00</div>
                </div> -->
                <div class="waveform-container">
                  <div class="waveform" ref="waveform1" id="waveform1"></div>
                  <div class="progress-bar" id="progress1"></div>
                </div>
              </div>
            </div>
            <div class="content-video" v-if="shipin.length>0">
              <div class="video-grid">
                <div class="video-item">
                  <video
                    class="hide-progress-bar"
                    ref="videoPlayer"
                    controls="false"
                    autoplay
                    loop
                    :src="shipin[0].fileUrl"
                    controlsList="nodownload"
                    preload="auto"
                  >
                    您的浏览器不支持 video 标签。
                  </video>
                </div>
              </div>
            </div>
            <div class="content-video" v-if="shipin.length>1">
              <div class="video-grid">
                <div class="video-item">
                  <video
                          class="hide-progress-bar"
                          ref="videoPlayer"
                          controls="false"
                          autoplay
                          loop
                          :src="shipin[1].fileUrl"
                          controlsList="nodownload"
                          preload="auto"
                  >
                    您的浏览器不支持 video 标签。
                  </video>
                </div>
              </div>
            </div>
            <div class="content-video" v-if="shipin.length>2">
              <div class="video-grid">
                <div class="video-item">
                  <video
                          class="hide-progress-bar"
                          ref="videoPlayer"
                          controls="false"
                          autoplay
                          loop
                          :src="shipin[2].fileUrl"
                          controlsList="nodownload"
                          preload="auto"
                  >
                    您的浏览器不支持 video 标签。
                  </video>
                </div>
              </div>
            </div>
            <div class="img-item" v-if="chongqing.length==1">
              <img class="image" :src="chongqing[0].fileUrl" alt="" />
            </div>
            <div class="img-item" v-if="chongqing.length==2">
              <img class="image" :src="chongqing[1].fileUrl" alt="" />
            </div>
            <div class="img-item" v-if="chongqing.length==3">
              <img class="image" :src="chongqing[2].fileUrl" alt="" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="device-tabs">
      <div
        v-for="item in list"
        :key="item.id"
        :class="['device-tab', { active: active === item.id }]"
        @click="handleDeviceClick(item.id, item.data)"
      >
        <span>{{ item.name }}</span>
      </div>
    </div>
  </div>
</template> 

<script>
import WaveSurfer from "wavesurfer.js"
import {EventBus} from "../../utils/event-bus";
export default {
  name: "Center",
  data() {
    return {
      updateTime:"",
      active: "road",
      hongwai:[],
      shengwen: null,
      shipin: [],
      chongqing: [],
      wavesurfer: null,
      isPlaying: false,
      autoplayAttempted: false,
      card: null,
      timeDisplay: null,
      evnResults:null,
      list: [
        { id: "road", name: "体验之路", data: "" },
        { id: "science-education", name: "科普教育", data: "" }
      ],
      points: [
        {
          id: 1,
          name: "林鸟声纹",
          num: 0,
          img: require("@/assets/img/points1.png"),
        },
        {
          id: 2,
          name: "水鸟视频",
          num: 0,
          img: require("@/assets/img/points2.png"),
        },
        {
          id: 3,
          name: "兽类红外",
          num: 0,
          img: require("@/assets/img/points3.png"),
        },
        {
          id: 4,
          name: "环境监测",
          num: 0,
          img: require("@/assets/img/points4.png"),
        },
        {
          id: 5,
          name: "智能虫情",
          num: 0,
          img: require("@/assets/img/points5.png"),
        },
        {
          id: 6,
          name: "植物物候",
          num: 0,
          img: require("@/assets/img/points6.png"),
        },
      ],
      airData: [
        {
          id: 1,
          name: "温度",
          value: "23.5℃",
          img: require("@/assets/img/air1.png"),
        },
        {
          id: 2,
          name: "湿度",
          value: "45%",
          img: require("@/assets/img/air2.png"),
        },
        {
          id: 3,
          name: "PM2.5",
          value: "123",
          img: require("@/assets/img/air3.png"),
        },
        {
          id: 4,
          name: "PM10",
          value: "123",
          img: require("@/assets/img/air4.png"),
        },
        {
          id: 5,
          name: "PM10",
          value: "123",
          img: require("@/assets/img/air4.png"),
        },
        {
          id: 6,
          name: "",
          value: "",
          img: "",
        },
      ],
      pointName:''
    };
  },
  mounted() {},
  created() {
    EventBus.$on('set-route-item', (message) => {
      this.pointName=message.title;
      this.getItemQJT(message.id);
    })
  },
  methods: {
    getItemQJT(id){
      var map={
        observationId:id.toString(),
        orderField:"sort",
        order:"asc"
      };
      this.$api.route.getItemList(map).then(response => {
        if (response) {
          this.hongwai=[];
          this.shipin=[];
          this.shengwen=null;
          this.chongqing=[];
          for (let i = 0; i < this.points.length; i++){
            this.points[i].num=0;
          }
          for (let i = 0; i < response.length; i++) {
            switch (response[i].type) {
              case "红外":
                this.getResult("hongwai",response[i].value.toString());
                this.points[2].num++;
                break;
              case "声纹":
                this.getResult("shengwen",response[i].value.toString());
                this.points[0].num++;
                break;
              case "视频":
                this.getResult("shipin",response[i].value.toString());
                this.points[1].num++;
                break;
              case "虫情":
                this.getResult("chongqing",response[i].value.toString());
                this.points[4].num++;
                break;
              case "气象":
                this.getEvnData("qixiang",response[i].value.toString());
                this.points[3].num++;
                break;
              case "土壤":
                this.getEvnData("turang",response[i].value.toString());
                this.points[3].num++;
                break;
            }
          }
          if(this.hongwai.length+this.shipin.length+this.chongqing.length>3){
            if(this.hongwai.length==3){
              this.hongwai.pop();
            }
            if(this.shipin.length==3){
              this.shipin.pop();
            }
            if(this.chongqing.length==3){
              this.chongqing.pop();
            }
          }
        }
      });
    },
    getResult(type,id){
      var ids=[];
      ids.push(id);
      this.$api.species.getCollectListByIds(type,ids).then(res => {
        switch (type) {
          case "hongwai":
            if(res){
              if(res.length>0){
                this.hongwai.push(res[0]);
              }
              if(res.length>1){
                this.hongwai.push(res[1]);
              }
              if(res.length>2){
                this.hongwai.push(res[2]);
              }
            }
            break;
          case "shengwen":
            this.shengwen=res&&res.length?res[0]:null;
            if(this.shengwen){
              setTimeout(() => {
                this.initWaveSurfers()
              }, 2000)
            }
            break;
          case "shipin":
            if(res){
              if(res.length>0){
                this.shipin.push(res[0]);
              }
              if(res.length>1){
                this.shipin.push(res[1]);
              }
              if(res.length>2){
                this.shipin.push(res[2]);
              }
            }
            break;
          case "chongqing":
            if(res){
              if(res.length>0){
                this.chongqing.push(res[0]);
              }
              if(res.length>1){
                this.chongqing.push(res[1]);
              }
              if(res.length>2){
                this.chongqing.push(res[2]);
              }
            }
            break;
        }
      });
    },
    getEvnData(type,id){
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth() + 1; // 月份从0开始，需要加1
      const day = currentDate.getDate();
      const hours = String(currentDate.getHours()).padStart(2, "0");
      const minutes = String(currentDate.getMinutes()).padStart(2, "0");
      const seconds = String(currentDate.getSeconds()).padStart(2, "0");
      this.updateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      this.$api.environment.getCollectList(type, id)
              .then((res) => {
                this.evnResults = res;
              });
    },
    handleDeviceClick(id, data) {
      this.active = id;
      if(id == "science-education"){
        this.$router.push('/ScienceEducation');
      }
    },
    initWaveSurfers() {
      try {
        this.isPlaying = false
        this.autoplayAttempted = false

        const waveform = this.$refs.waveform1

        this.card = document.getElementById('card')

        // this.timeDisplay = document.getElementById('time1')


        this.wavesurfer = WaveSurfer.create({
          container: waveform,
          waveColor: '#4a90e2',
          progressColor: '#2c3e50',
          cursorColor: '#e74c3c',
          barWidth: 1,
          barRadius: 2,
          cursorWidth: 1,
          height: 30,
          barGap: 1,
          responsive: true,
          normalize: true,
          interact: false
        })

        this.wavesurfer.on('error', function(error) {
          console.error('WaveSurfer错误:', error)
        })

        this.wavesurfer.load(this.shengwen.fileUrl);

        this.wavesurfer.on('ready', () => {
          // this.updateTimeDisplay(0, this.wavesurfer.getDuration())

          if (this.autoplayAttempted) {
            this.autoplayAttempted = true

            setTimeout(() => {
              this.playAudio()
            }, 2000)
          }
        })

        this.wavesurfer.on('audioprocess', () => {
          // this.updateTimeDisplay(this.wavesurfer.getCurrentTime(), this.wavesurfer.getDuration())
          this.updateProgressBar(this.wavesurfer.getCurrentTime() / this.wavesurfer.getDuration())
        })

        this.wavesurfer.on('finish', () => {
          this.isPlaying=false;
          this.playNextAudio();
        })


      } catch (error) {
        console.error('Error initializing wave surfers:', error)
      }
    },
    loadAudio() {
      if (!this.wavesurfer) return
      this.wavesurfer.stop()
    },
    attemptAutoplay() {
      const playPromise = this.wavesurfer.play()

      if (playPromise !== undefined) {
        playPromise.then(() => {
          this.isPlaying = true
        })
                .catch(error => {
                  console.log('自动播放被阻止:', error)
                })
      }
    },
    updateActiveCard() {
      // this.card.classList.remove('active')
      // this.card.classList.add('active')
    },
    playAudio() {

      if (this.isPlaying) {
        this.isPlaying=false;
        this.wavesurfer.stop();
        // this.updateActiveCard();
        return;
      }

      const playPromise = this.wavesurfer.play()
      if (playPromise !== undefined) {
        playPromise.then(() => {
          this.isPlaying = true
          this.card.classList.add('active')
        })
                .catch(error => {
                  console.error('播放失败:', error)
                })
      }
    },
    playNextAudio() {
      // this.card.classList.remove('active')
      setTimeout(() => {
        this.playAudio()
      }, 3000)
    },
    updateTimeDisplay( currentTime, duration) {
      if (this.timeDisplay) {
        this.timeDisplay.textContent = `${this.formatTime(currentTime)} / ${this.formatTime(duration)}`
      }
    },
    updateProgressBar(progress) {
      const progressBar = document.getElementById(`progress1`)
      if(progressBar) {
        progressBar.style.width = `${progress * 100}%`
      }
    },
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60)
      const secs = Math.floor(seconds % 60)
      return `${minutes}:${secs < 10 ? '0' : ''}${secs}`
    }
  },
};
</script>

<style lang="scss" scoped>
.device-tabs {
  display: flex;
  gap: 10px;
  padding: 10px 0;
  justify-content: center;
}

.device-tab {
  width: 197px;
  height: 60px;
  pointer-events: auto;
  color: #ccc;
  cursor: pointer;
  font-size: 14px;
  text-align: center;
  background: url("@/assets/img/species-center-tab-normal-bg.png") no-repeat
    center;
  background-size: 100% 100%;
  transition: all 0.3s ease;
  user-select: none;

  &.active {
    background-image: url("@/assets/img/species-center-tab-active-bg.png");
    color: #fff;
  }

  &:hover {
    color: #fff;
  }
  span {
    font-size: 18px;
    display: inline-block;
    margin-top: 24px;
  }
  div {
    font-size: 12px;
  }
}
.device-content {
  height: 180px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  overflow: hidden;
  bottom: 0;
  background:transparent;
  .dialog-title {
    color: #fff;
    line-height: 40px;
    width: 100%;
    padding-left: 30px;
    background:url('@/assets/img/home-center-4.png') no-repeat 0 center;
  }
  .points-content {
    height: 140px;
    overflow: hidden;
    width: 100%;
    border-radius: 10px;
    background: #063C6A;
    .content-item {
      float: left;
      height: 140px;
      &:nth-child(1) {
        line-height: 20px;
      }
      .content-item-points {
        padding: 0 15px;
        .unit-img {
          width: 11px;
          height: 12px;
          position: relative;
          top: 1px;
        }
        .unit-name {
          font-size: 10px;
          color: #fff;
          text-align: center;
          margin-right: 10px;
          margin-left: 5px;
        }
        .unit-num {
          font-size: 10px;
          text-align: center;
          color: #07ffe5;
        }
      }
    }
    .content-item:nth-child(2) {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      .layout-item:nth-child(1) {
        width: 100px;
        height: 140px;
        padding-left: 7px;
        margin-right: 7px;
        background: rgba(65, 123, 214, 0.2);
        .title {
          text-align: center;
          font-size: 10px;
          color: #fff;
          margin-top: 17px;
        }
        .air-value {
          text-align: center;
          font-size: 24px;
          color: #07ffe5;
          margin-top: 25px;
        }
        .air-level {
          text-align: center;
          font-size: 12px;
          color: #07ffe5;
          margin-top: 13px;
        }
        .air-time {
          text-align: center;
          font-size: 8px;
          color: #fff;
          margin-top: 12px;
        }
      }
      .layout-item:nth-child(2) {
        width: 126px;
        gap: 4px;
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        grid-template-rows: repeat(2, 1fr);
        img {
          width: 14px;
          height: 11px;
          position: relative;
          top: 2px;
        }
        .item {
          line-height: 15px;
          width: 53px;
          height: 38px;
          padding: 5px 0 0 5px;
          background: rgba(65, 123, 214, 0.2);
          text-align: center;
          align-items: center;
          font-size: 8px;
          color: #fff;
          img {
            position: relative;
            top: 1px;
          }
          .item-value {
            text-align: center;
            font-size: 8px;
            margin-top: 3px;
          }
        }
      }
    }
    .content-item:nth-child(3) {
      display: flex;
      gap: 4px;
      width: 474px;
      overflow-x: auto;
      overflow-y: hidden;
      .container {
        clear: both;
        width: 1000px;
        display: -webkit-box;
        display: -moz-box;
        display: -ms-box;
        display: -o-box;
        & > div {
          float: left;
          margin-right: 4px;
          &>div:last-child{
            margin-right: 0;
          }
        }
        .img-item {
          width: 156px;
          height: 128px;
        }
      }
      .content-video {
        background-color: #00112c;
        display: flex;
        justify-content: center;
        align-items: center;
        .video-item {
          video {
            object-fit: fill;
            width: 156px;
            height: 128px;
          }
        }
      }
    }
  }
}
.image{
  width: 100%;
  height: 100%;
  object-fit: fill;
}
.layout {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  gap: 4px;
  width: 250px;
  .layout-item {
    &:nth-child(1) {
      width: 88px;
    }
    .title {
      text-align: center;
      font-size: 10px;
    }
    .air-value {
      text-align: center;
      font-size: 24px;
      color: #07ffe5;
    }
    .air-level {
      text-align: center;
      font-size: 12px;
      color: #07ffe5;
    }
    .air-time {
      text-align: center;
      font-size: 6;
    }
  }
}
.audio-card {
  width: 156px;
  top: 10px;
  height: 120px;
  transition: all 0.3s ease;
  cursor: pointer;
  background: #000;
  /*&.active {*/
  /*  box-shadow: 0 0 0 3px #4a90e2, 0 10px 20px rgba(74, 144, 226, 0.3);*/
  /*  &::after {*/
  /*    content: "正在播放";*/
  /*    position: absolute;*/
  /*    top: 10px;*/
  /*    right: 10px;*/
  /*    background-color: #4a90e2;*/
  /*    color: white;*/
  /*    padding: 3px 8px;*/
  /*    font-size: 12px;*/
  /*    font-weight: bold;*/
  /*  }*/
  /*}*/
  .audio-image {
    padding-top: 6px;
    width: 100%;
    height: 90px;
    object-fit: fill;
  }
  .audio-content {
    height: 30px;
    display: flex;
    flex: 1;
    position: relative;
    top: -4px;
  }
  .audio-info {
    flex: 1;
    padding-right: 5px;
    h3 {
      padding-top: 5px;
      padding-left: 5px;
      margin: 0 0 8px 0;
      color: #2c3e50;
      font-size: 6px;
      height: 18px;
    }
    p {
      margin: 0;
      color: #7f8c8d;
      font-size: 6px;
    }
  }
}

.waveform-container {
  width: 100%;
  height: 30px;
  background-color: #f1f3f4;
  position: relative;
  overflow: hidden;
}

.waveform {
  width: 100%;
  height: 100%;
}

.progress-bar {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 0;
  background-color: rgba(74, 144, 226, 0.2);
  pointer-events: none;
}

.time-display {
  padding-left: 5px;
  font-size: 12px;
  color: #7f8c8d;
  margin-top: 5px;
  text-align: left;
}

.autoplay-message {
  text-align: center;
  color: #e74c3c;
  margin-bottom: 20px;
  font-size: 14px;
  display: none;
}
</style>
